﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net.Http;
using System.Net.NetworkInformation;
using DynamicDnsChanger.Extensions;
using DynamicDnsChanger.Extensions.Requester;
using System.Text.RegularExpressions;
using DynamicDnsChanger.MEF;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Microsoft.CSharp;
namespace DynamicDnsChanger.Tests
{

    [TestClass]
    public class IpInfo
    {
        readonly string CLOUDFLARE_EMAIL = "";
        readonly string CLOUDFLARE_TOKEN = "";

        public IpInfo()
        {
            if (String.IsNullOrEmpty(CLOUDFLARE_EMAIL) || String.IsNullOrEmpty(CLOUDFLARE_TOKEN))
            {
                using (var iniFile = new StreamReader(@"..\...\TestConfig.txt"))
                {
                    var strLine = iniFile.ReadLine();

                    while (strLine != null)
                    {
                        var pair = strLine.Split('=');
                        if (pair.Count() > 1)
                        {
                            if (pair[0].Trim() == "email")
                            {
                                CLOUDFLARE_EMAIL = pair[1].Trim();
                            }
                            else if (pair[0].Trim() == "token")
                            {
                                CLOUDFLARE_TOKEN = pair[1].Trim();
                            }
                        }
                        strLine = iniFile.ReadLine();
                    }
                }

            }
        }

        [TestMethod]
        public void GetIpInfoFromWeb()
        {
            var sites = new string[] { "http://checkip.mtgsy.net/" };

            var _client = new HttpClient();
            var result = _client.GetStringAsync(sites[0].ToString());
            var res = result.Result;

            Assert.IsNotNull(res);
            Console.WriteLine(res);
        }
        [TestMethod]
        public void GetIpFromEthernet()
        {
            var IP = "";
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    IP = nic.Description;
                    Console.WriteLine(IP);

                }
            }
            Assert.IsFalse(String.IsNullOrEmpty(IP));
        }

        [TestMethod]
        public void GetAllCloudFlareDnsEntry()
        {
            var clouflareApiUrl = "https://www.cloudflare.com/api_json.html?tkn={0}&email={1}&a=rec_load_all&z={2}";
            var _client = new HttpClient();
            var result = _client.GetStringAsync(String.Format(clouflareApiUrl, CLOUDFLARE_TOKEN, CLOUDFLARE_EMAIL, "recursosonline.com.br"));
            var res = result.Result;
            //var subdomains = new JsonReader()
            JToken token = JObject.Parse(res);
            var results = JsonConvert.DeserializeObject<dynamic>(res);
            foreach (var item in results.response.recs.objs)
            {
                Console.WriteLine(item.display_name + ":" + item.rec_id);
            }
            Assert.IsNotNull(results);
            Assert.IsNotNull(res);
        }
        [TestMethod]
        public void CloudFlareUpdateIP()
        {
            //vilaolimpia: 147315937
            //morumbi: 147315856
            //cam: 147316048
            //pabx: 147315919
            //pbx: 147564250

            var hostID = "149436343";
            var clouflareApiUrl = "https://www.cloudflare.com/api_json.html?tkn={0}&email={1}&a=rec_edit&z={2}&type=A&name={3}&content=200.235.161.89&service_mode=1&ttl=1&id={4}";
            using (var _client = new HttpClient())
            {
                var result = _client.GetStringAsync(String.Format(clouflareApiUrl, CLOUDFLARE_TOKEN, CLOUDFLARE_EMAIL, "recursosonline.com.br", "api", hostID));
                var res = result.Result;
                Assert.IsNotNull(res);
                Console.WriteLine(res);
            }

        }
        [TestMethod]
        public void Verifica_Se_Request_Esta_Funcionando()
        {
            var _request = new Requester();
            var s = _request.GetString("http://checkip.mtgsy.net/");
            Console.WriteLine(s);
            Assert.IsNotNull(s);
        }
        [TestMethod]
        public void Testa_RegularExpression_IP()
        {
            var p = "Your ip address is detected as  200.156.789.1";
            String IPADDRESS_PATTERN =
           "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
            var ip = Regex.Match(p, IPADDRESS_PATTERN).Groups[0].Value;
            Console.WriteLine(ip);
            Assert.IsNotNull(ip.Trim());
        }

        [TestMethod]
        public void Testa_CheckIP()
        {
            string PluginPath = @"X:\Projetos\DynamicDnsChanger\DynamicDnsChanger.Extensions.CheckIP\bin\Debug";
            IEnumerable<ICheckIP> CheckIP_Plugins;
            var r = new Requester();
            GenericPluginLoader<ICheckIP> loader = new GenericPluginLoader<ICheckIP>(PluginPath, r);
            CheckIP_Plugins = loader.Plugins;
            Assert.IsNotNull(CheckIP_Plugins);
            var checkIp = CheckIP_Plugins.FirstOrDefault();
            checkIp.StatusChange += (s, evt) =>
            {
                Console.WriteLine(evt.TypeOfMessage.ToString() + " - " + evt.Message);
            };
            checkIp.Check();
            //System.Threading.Thread.Sleep(2000);
            //Assert.IsNotNull(CheckIP_Plugins.GetEnumerator().Current);
        }
        [TestMethod]
        public void Verifica_Se_CloudFlare_Funciona()
        {
            string PluginPath = @"X:\Projetos\DynamicDnsChanger\DynamicDnsChanger\Plugins";
            var r = new Requester();
            GenericPluginLoader<IUpdater> loader = new GenericPluginLoader<IUpdater>(PluginPath, r);
            var cloudFlare = loader.Plugins.FirstOrDefault();
            cloudFlare.StatusChange += (s, evt) =>
            {
                Console.WriteLine(evt.TypeOfMessage.ToString() + " - " + evt.Message);
            };
            cloudFlare.Update("200.235.161.121");
            System.Threading.Thread.Sleep(10000);
            cloudFlare.Update("200.235.161.122");

        }

        [TestMethod]
        public void Verifica_Se_NoIP_Funciona()
        {
            string PluginPath = @"X:\Projetos\DynamicDnsChanger\DynamicDnsChanger\bin\Release\Plugins";
            var r = new Requester();
            GenericPluginLoader<IUpdater> loader = new GenericPluginLoader<IUpdater>(PluginPath, r);
            var noIp = loader.Plugins.Where(x => x.Name == "No-IP").FirstOrDefault();
            noIp.StatusChange += (s, evt) =>
            {
                Console.WriteLine(evt.TypeOfMessage.ToString() + " - " + evt.Message);
            };
            noIp.Update("200.235.161.155");
            System.Threading.Thread.Sleep(1000);
            //noIp.Update("200.235.161.122");

        }
        [TestMethod]
        public void Verifica_Se_ZoneEdit_Funciona()
        {
            string PluginPath = @"X:\Projetos\DynamicDnsChanger\DynamicDnsChanger\bin\Release\Plugins";
            var r = new Requester();
            GenericPluginLoader<IUpdater> loader = new GenericPluginLoader<IUpdater>(PluginPath, r);
            var noIp = loader.Plugins.Where(x => x.Name == "ZoneEdit").FirstOrDefault();
            noIp.StatusChange += (s, evt) =>
            {
                Console.WriteLine(evt.TypeOfMessage.ToString() + " - " + evt.Message);
            };
            noIp.Update("200.235.161.155");
            System.Threading.Thread.Sleep(1000);
            //noIp.Update("200.235.161.122");

        }
        [TestMethod]
        public void Verifica_Se_DynDNS_Funciona()
        {
            string PluginPath = @"X:\Projetos\DynamicDnsChanger\DynamicDnsChanger\bin\Release\Plugins";
            var r = new Requester();
            GenericPluginLoader<IUpdater> loader = new GenericPluginLoader<IUpdater>(PluginPath, r);
            var noIp = loader.Plugins.Where(x => x.Name == "DynDNS").FirstOrDefault();
            noIp.StatusChange += (s, evt) =>
            {
                Console.WriteLine(evt.TypeOfMessage.ToString() + " - " + evt.Message);
            };
            noIp.Update("200.235.161.155");
            System.Threading.Thread.Sleep(1000);
            //noIp.Update("200.235.161.122");

        }
        [TestMethod]
        public void ReadConfigFromFile()
        {
            var email = "";
            var token = "";
            var zone = "";
            var domains = "";
            using (var iniFile = new StreamReader(Environment.CurrentDirectory + @"\DynamicDnsChanger.Extensions.CloudFlare.ini"))
            {
                var strLine = iniFile.ReadLine();

                while (strLine != null)
                {
                    var pair = strLine.Split('=');
                    if (pair.Count() > 1)
                    {
                        if (pair[0].Trim() == "email")
                        {
                            email = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "zone")
                        {
                            zone = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "token")
                        {
                            token = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "domains")
                        {
                            domains = pair[1].Trim();
                        }
                    }
                    strLine = iniFile.ReadLine();
                }
            }
            Assert.IsTrue(email.Length > 0);
            Assert.IsTrue(zone.Length > 0);
            Assert.IsTrue(token.Length > 0);
            Assert.IsTrue(domains.Length > 0);
            Console.WriteLine(email);
            Console.WriteLine(zone);
            Console.WriteLine(token);
            Console.WriteLine(domains);
        }
    }
}
